package com.ruoyi.web.controller.mini;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.MiniLoginUser;
import com.ruoyi.framework.security.context.UserContextHolder;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.MyUser;
import com.ruoyi.system.service.IMyUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * 用户相关接口
 */
@RestController
@RequestMapping("/mini/user")
@Api(tags = "用户相关接口")
public class UserController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private IMyUserService userService;

    /**
     * 用户登录
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public AjaxResult login(@RequestBody String code){
        //微信登录
        MyUser user = userService.login(code);

        // 生成token
        MiniLoginUser loginUser = new MiniLoginUser();
        loginUser.setId(user.getId());
        loginUser.setType(0);
        String token = tokenService.createToken(loginUser);

        // 返回结果
        HashMap<String, Object> res = new HashMap<>();
        res.put("token", token);
        res.put("loginUser", loginUser);
        return success(res);
    }

    /**
     * 用户信息
     */
    @GetMapping("/info")
    @ApiOperation("用户信息")
    public AjaxResult info(Long userId) {
        if (userId == null) {
            userId = UserContextHolder.getCurrentUser().getId();
        }
        MyUser user = userService.getById(userId);
        return success(user);
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/update")
    @ApiOperation("修改用户信息")
    public AjaxResult update(@RequestBody MyUser user) {
        return success(userService.updateById(user));
    }

}
